package com.trinity.campus.controller;

import com.trinity.campus.domain.BindBody;
import com.trinity.campus.domain.CampusStudents;
import com.trinity.campus.domain.CampusUserStudent;
import com.trinity.campus.service.ICampusStudentsService;
import com.trinity.common.annotation.Log;
import com.trinity.common.constant.DeptConstants;
import com.trinity.common.core.controller.BaseController;
import com.trinity.common.core.domain.AjaxResult;
import com.trinity.common.core.domain.entity.SysDept;
import com.trinity.common.core.page.TableDataInfo;
import com.trinity.common.enums.BusinessType;
import com.trinity.common.utils.poi.ExcelUtil;
import com.trinity.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学生Controller
 *
 * @author trinity
 * @date 2023-11-18
 */
@RestController
@RequestMapping("/campus/students")
public class CampusStudentsController extends BaseController {
    @Resource
    private ICampusStudentsService campusStudentsService;

    @Resource
    private ISysDeptService deptService;

    /**
     * 查询学生列表
     */
    @PreAuthorize("@ss.hasPermi('campus:students:list')")
    @GetMapping("/list")
    public TableDataInfo list(CampusStudents campusStudents) {
        startPage();
        //查询未删除的
        campusStudents.setDelFlag("0");
        List<CampusStudents> list = campusStudentsService.selectCampusStudentsList(campusStudents);
        return getDataTable(list);
    }

    /**
     * 查询学生列表
     */
    @PreAuthorize("@ss.hasPermi('campus:students:list')")
    @GetMapping("/org/{deptId}")
    public AjaxResult StulistByListDeptId(@PathVariable("deptId") Long deptId) {
        List<CampusStudents> list = campusStudentsService.selectCampusStudentsListByDeptId(deptId);
        return success(list);
    }

    @Log(title = "导入学生", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('campus:students:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<CampusStudents> util = new ExcelUtil<>(CampusStudents.class);
        List<CampusStudents> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = campusStudentsService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载学生导入模板
     *
     * @param response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<CampusStudents> util = new ExcelUtil<>(CampusStudents.class);
        List<SysDept> depts = deptService.selectDeptSchoolList(new SysDept());
        Map<String, List<String>> combo = depts.stream()
                .collect(Collectors.groupingBy(
                        dept -> {
                            String deptType = dept.getDeptType();
                            switch (deptType) {
                                case "X":
                                    return DeptConstants.DEPT_TYPE_SCHOOL;
                                case "Y":
                                    return DeptConstants.DEPT_TYPE_COLLEGE;
                                case "Z":
                                    return DeptConstants.DEPT_TYPE_MAJOR;
                                case "B":
                                    return DeptConstants.DEPT_TYPE_CLASS;
                                default:
                                    return ""; // Handle other cases if necessary
                            }
                        },
                        Collectors.mapping(SysDept::getDeptName, Collectors.toList())
                ));
        combo.values().removeIf(List::isEmpty);
        util.importTemplateExcel(response, "学生数据导入模板", combo);
    }

    /**
     * 导出学生列表
     */
    @PreAuthorize("@ss.hasPermi('campus:students:export')")
    @Log(title = "学生", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CampusStudents campusStudents) {
        List<CampusStudents> list = campusStudentsService.selectCampusStudentsList(campusStudents);
        ExcelUtil<CampusStudents> util = new ExcelUtil<>(CampusStudents.class);
        util.exportExcel(response, list, "学生数据");
    }

    /**
     * 获取学生详细信息
     */
    @PreAuthorize("@ss.hasPermi('campus:students:query')")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") Long studentId) {
        return success(campusStudentsService.selectCampusStudentsByStudentId(studentId));
    }

    /**
     * 新增学生
     */
    @PreAuthorize("@ss.hasPermi('campus:students:add')")
    @Log(title = "学生", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CampusStudents campusStudents) {
        return toAjax(campusStudentsService.insertCampusStudents(campusStudents));
    }

    /**
     * 修改学生
     */
    @PreAuthorize("@ss.hasPermi('campus:students:edit')")
    @Log(title = "学生", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/put", method = {RequestMethod.POST})
    public AjaxResult edit(@RequestBody CampusStudents campusStudents) {

        //1.检查 学号是否唯一
        if (!campusStudentsService.checkStudentNoUnique(campusStudents)) {
            return error("修改学生'" + campusStudents.getStuNo() + "'失败，学号已存在");
        }
        campusStudents.setUpdateBy(getUsername());
        return toAjax(campusStudentsService.updateCampusStudents(campusStudents));
    }

    /**
     * 删除学生:逻辑删除
     */
    @PreAuthorize("@ss.hasPermi('campus:students:remove')")
    @Log(title = "学生", businessType = BusinessType.DELETE)
    @RequestMapping(value = "/{studentIds}/delete", method = {RequestMethod.POST})
    public AjaxResult remove(@PathVariable Long[] studentIds) {
        return toAjax(campusStudentsService.setStudentTombstoneByStudentIds(studentIds));
    }

    /**
     * 微信用户绑定学生信息
     */
    @Log(title = "微信用户绑定学生", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/bindUser", method = {RequestMethod.POST})
    public AjaxResult wxBindUser(@RequestBody @Valid BindBody bindBody) {
        return campusStudentsService.bindStudent(bindBody);
    }

    /**
     * 查询微信用户绑定学生信息
     */
    @Log(title = "微信用户绑定学生", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/bindUser", method = {RequestMethod.GET})
    public AjaxResult getWxBindStudent() {
        AjaxResult result = AjaxResult.success();
        CampusUserStudent bindStudent = campusStudentsService.getBindStudent(getUserId());
        result.put("student", bindStudent != null ? bindStudent.getCampusStudent() : null);
        return result;
    }
}
